package com.tj.jinzao.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tj.jinzao.R;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.base.ConstantApp;
import com.tj.jinzao.callback.IUploadView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.Identification;
import com.tj.jinzao.model.Target;
import com.tj.jinzao.model.User;
import com.tj.jinzao.presenter.IdentifyPresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.widgets.MaxTextLengthFilterFH;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

import static com.luck.picture.lib.config.PictureConfig.CHOOSE_REQUEST;

/**
 * 实名认证界面
 * Created by wjy on 2019/1/5.
 */
public class MyIdentificationRealActivity extends BaseActivity<IdentifyPresenter> implements IUploadView<Identification> {

    @BindViews({R.id.iv_card_1, R.id.iv_card_2, R.id.iv_card_3})
    List<ImageView> mCardViews;
    @BindView(R.id.et_number)
    EditText mNumberView;
    @BindView(R.id.et_name)
    EditText mNameView;
    @BindView(R.id.bt_submit)
    Button bt_submit;

    private String mImagePath[];
    private User user;

    @Override
    protected void setupView() {
        super.setupView();
        mImagePath = new String[3];
        mPresenter.isRealName();
        user=UserManager.getInstance().getUser();
        if(user==null){
            return;
        }
        if(user.getVerified()==2){
            bt_submit.setText("认证通过");
            bt_submit.setBackgroundResource(R.drawable.bg_login_grey);
        }else if(user.getVerified()==3||user.getVerified()==1){
            bt_submit.setBackgroundResource(R.drawable.bg_login_button);
            bt_submit.setText("提交");
        }else if(user.getVerified()==4){
            bt_submit.setText("审核中");
            bt_submit.setBackgroundResource(R.drawable.bg_login_grey);
        }else {
            bt_submit.setText("提交");
            bt_submit.setBackgroundResource(R.drawable.bg_login_button);
        }
        mNameView.setFilters(new InputFilter[]{new MaxTextLengthFilterFH(12, MyIdentificationRealActivity.this,"名称限12字以内")});
    }

    /**
     * 禁止EditText输入空格、表情和换行符以及特殊符号&&
     *
     * @param editText EditText输入框
     */
    public static void setEditTextInputSpace(EditText editText) {
        final Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher emojiMatcher = emoji.matcher(source);
                //禁止特殊符号
                String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                //禁止输入空格
                if (source.equals(" ") || source.toString().contentEquals("\n")) {
                    return "";
                    //禁止输入表情
                } else if (emojiMatcher.find()) {
                    return "";
                } else if (matcher.find()) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }
    @Override
    public int getLayoutResource() {
        return R.layout.activity_my_identification_real;
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }

    private int mType = 0;

    //身份证正面 照片
    @OnClick(R.id.rl_identification_card_layout)
    public void front() {
        if(user.getVerified()==2||user.getVerified()==4){
            return;
        }
        mType = 0;
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .compress(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    //身份证正面 照片
    @OnClick(R.id.rl_identification_card_behind_layout)
    public void behind() {
        if(user.getVerified()==2||user.getVerified()==4){
            return;
        }

        mType = 1;
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .compress(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    //手持身份证 照片
    @OnClick(R.id.rl_identification_hand_layout)
    public void hand() {
        if(user.getVerified()==2||user.getVerified()==4){
            return;
        }
        mType = 2;
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .compress(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia localMedia : selectList) {
                        mImagePath[mType] = localMedia.isCompressed() ? localMedia.getCompressPath() : localMedia.getPath();
                        Glide.with(this).load(mImagePath[mType]).into(mCardViews.get(mType));
                    }
                    break;
            }
        }
    }

    @OnClick(R.id.bt_submit)
    public void submit() {
    if(user!=null&&(user.getVerified()==3||user.getVerified()==1)){
        String name = mNameView.getText().toString().trim();
        String number = mNumberView.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showToast(this, "请输入姓名");
            return;
        } else if (TextUtils.isEmpty(number)) {
            ToastUtils.showToast(this, "请输入身份证号");
            return;
        }
        for (String path : mImagePath) {
            if (TextUtils.isEmpty(path)) {
                ToastUtils.showToast(this, "请上传照片");
                return;
            }
        }
        if(ConstantApp.isFastDoubleClick(1500)){
            return;
        }
        index=0;
        if(mImagePath[0]==null||mImagePath[1]==null||mImagePath[2]==null){
            ToastUtils.showToast(this, "请上传3张照片");
            return;
        }
        uploadFile();

    }
    }

    private void uploadFile() {
        if(!mImagePath[0].startsWith(Constant.SD_ROOT)&&!mImagePath[1].startsWith(Constant.SD_ROOT)&&!mImagePath[2].startsWith(Constant.SD_ROOT)){
            mPresenter.sendRealName(MyIdentificationRealActivity.this,mNameView.getText().toString().trim(), mNumberView.getText().toString().trim(), mImagePath[0], mImagePath[1], mImagePath[2]);
            return;
        }

        if(mImagePath[0]!=null){
            if(mImagePath[0].startsWith(Constant.SD_ROOT)){
                mPresenter.uploadFile(mImagePath[0]);
            }
        }
        if(mImagePath[1]!=null){
            if(mImagePath[1].startsWith(Constant.SD_ROOT)){
                mPresenter.uploadFile(mImagePath[1]);
            }
        }
        if(mImagePath[2]!=null){
            if(mImagePath[2].startsWith(Constant.SD_ROOT)){
                mPresenter.uploadFile(mImagePath[2]);
            }
        }
    }
    private int index=0;

    @Override
    public void onUploadSuccess(String path, String url) {
        index++;
        for (int i=0;i<mImagePath.length;i++) {
            if (TextUtils.equals(mImagePath[i], path)) {
                 mImagePath[i] = url;
                break;
            }
        }
        if(!mImagePath[0].startsWith(Constant.SD_ROOT)&&!mImagePath[1].startsWith(Constant.SD_ROOT)&&!mImagePath[2].startsWith(Constant.SD_ROOT)){
            mPresenter.sendRealName(MyIdentificationRealActivity.this,mNameView.getText().toString().trim(), mNumberView.getText().toString().trim(), mImagePath[0], mImagePath[1], mImagePath[2]);
        }

    }

    @Override
    public void onCaseSuccess(List<Target> list) {

    }

    @Override
    public void onCaseFailed(String msg) {

    }

    @Override
    public Activity getContext() {
        return this;
    }
    private int isFirst=0;

    @Override
    public void onRequestSuccess(Identification identification) {
        if(identification!=null){
            if(identification.getFrontSideImgurl()!=null){
                mNameView.setText(identification.getRealName());
                mNumberView.setText(identification.getIdCard());
                mImagePath[0]=identification.getFrontSideImgurl();
                Glide.with(this).load(Constant.IMAGE_PREFIX+mImagePath[0]).into(mCardViews.get(0));
            } if(identification.getBackSideImgurl()!=null){
                mImagePath[1]=identification.getBackSideImgurl();
                Glide.with(this).load(Constant.IMAGE_PREFIX+mImagePath[1]).into(mCardViews.get(1));
            }if(identification.getHandHeldImgurl()!=null){
                mImagePath[2]=identification.getHandHeldImgurl();
                Glide.with(this).load(Constant.IMAGE_PREFIX+mImagePath[2]).into(mCardViews.get(2));
            }
        }
        if(isFirst>0){
            user.setVerified(4);
            UserManager.saveUserData(user);
            ToastUtils.showToast(MyIdentificationRealActivity.this,"实名认证申请已提交");
            finish();
        }
        isFirst++;

    }

    @Override
    public void onRequestNoData(String message) {

    }

    @Override
    public void onRequestError(String error_message) {
        ToastUtils.showToast(MyIdentificationRealActivity.this,error_message);

    }

    @Override
    protected IdentifyPresenter createPresenter() {
        return new IdentifyPresenter(this);
    }
}
